//
//  Project_Step5ViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/22.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Project_Step5ViewController.h"
#import "Project_Step4ViewController.h"
#import "Project_Step6ViewController.h"
#import "BottomActionView.h"
#import "Project_TabViewController.h"
#import "KqnRsjInfoData.h"
#import "SystemConfigTableViewCell.h"
#import "EditorTableViewCell.h"
#import "MachineSelectViewController.h"
#import "MachineSelectTableViewCell.h"
#import "KqnRsjInfoData.h"
#import "ProjectManager.h"
#import <MBProgressHUD.h>
#import "SNJMachineSelectViewController.h"
#import "GuidData.h"
#import "UITapView.h"
#import "SelectXSViewController.h"
#import "ProductListViewController.h"
#import "Project_Step8ViewController.h"
#import "ProjectContentViewController.h"

#define CELL_TYPE_SYSTEM 0
#define CELL_TYPE_MACHINE 1
#define CELL_TYPE_ROOM 2

@interface Project_Step5ViewController (){
    MBProgressHUD *HUD;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomActionView *footerView;

@end

@implementation Project_Step5ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    
}

/**
 *  初始化数据
 */
- (void)initData {
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"热水机配置";
    
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //添加按钮
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(onAddBtnClick)];
    self.navigationItem.rightBarButtonItem = addBtn;
    
    
    //底部的上一步，下一步按钮
    self.footerView = [[BottomActionView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    __block Project_Step5ViewController *tmp = (Project_Step5ViewController*)self;
    [self.footerView addLeftBtnBlock:^(id obj) {
        //TODO
        [[ProjectManager manager]goLastPage];
        [tmp.navigationController popViewControllerAnimated:YES];
        
    }];
    [self.footerView addRightBtnBlock:^(id obj) {
        [[ProjectManager manager]goNextPage];
        [tmp loadNextPage];
    }];
    [self.footerView setLeftBtnTitle:@"上一步" andRightBtnTitle:@"下一步" andCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
    [self.view addSubview:self.footerView];
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavBottom] style:UITableViewStylePlain];
    [self.tableView registerClass:[SystemConfigTableViewCell class] forCellReuseIdentifier:@"system"];
    [self.tableView registerClass:[EditorTableViewCell class] forCellReuseIdentifier:@"edit"];
    [self.tableView registerClass:[MachineSelectTableViewCell class] forCellReuseIdentifier:@"equip"];
    self.tableView.backgroundView = [[UIView alloc]init];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    //去掉多余的分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)loadNextPage {
    //先更新总步骤信息
    if (![Tools isEmpty:kProject.water_cleaner_series]) {
        Project_Step6ViewController *view = [Project_Step6ViewController new];
        [self.navigationController pushViewController:view animated:YES];
    } else {
        //报告页
        Project_Step8ViewController *view = [Project_Step8ViewController new];
        view.userName = kProject.name;
        view.project_id = kProject.project_id;
        view.project_name = kProject.project_name;
        [self.navigationController pushViewController:view animated:YES];
    }
}


#pragma mark - 事件响应
/**
 *  直接跳转到项目页面
 */
-(void)onBackToProject {
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[Project_TabViewController class]]) {
            [(Project_TabViewController*)tmp refreshData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}


//添加一套系统
-(void)onAddBtnClick {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kProject.project_id forKey:@"project_id"];
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_KQNRSJ_SYSTEM_ADD token:[AccountManager manager].token paramDic:params resultClass:[KqnrsjSystemData class] success:^(KqnrsjSystemData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.kqnrsj_systems addObject:obj];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"添加失败！"];
    }];
}

//修改系统面积
-(void)modifySystemBathtub:(int)bathtub_number andPerson:(int)person_number inSeciont:(NSInteger)section {
    KqnrsjEquipData *item = [kProject.kqnrsj_systems objectAtIndex:section];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[item project_kqnrsj_system_id] forKey:@"project_kqnrsj_system_id"];
    [params setValue:@(bathtub_number) forKey:@"bathtub_number"];
    [params setValue:@(person_number) forKey:@"person_number"];
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_KQNRSJ_SYSTEM_PARAM token:[AccountManager manager].token paramDic:params resultClass:[KqnrsjSystemData class] success:^(KqnrsjSystemData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.kqnrsj_systems replaceObjectAtIndex:section withObject:obj];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"选型失败！"];
    }];
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return kProject.kqnrsj_systems.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    KqnrsjSystemData *item = [kProject.kqnrsj_systems objectAtIndex:section];
    if (item.equips != nil) {
        return 4 + item.equips.count;
    }
    return 4;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KqnrsjSystemData *item =  [kProject.kqnrsj_systems objectAtIndex:indexPath.section];
    if (indexPath.row == 0) {
        //配置cell
        SystemConfigTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"system"];
        [cell setInfoStr:[NSString stringWithFormat:@"总用水量：%.1fL", item.water_volume]];
        [cell setTitleStr:item.system_name];
        
        //滑动按钮
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.tag = 1000+indexPath.section;
        
        return cell;
    } else if (indexPath.row == 1) {
        //浴缸数cell
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        [cell setTitle:@"浴缸数"];
        [cell setNumber:item.bathtub_number andUnit:@"个"];
        cell.SteperValueChangedBlock = ^(int number){
            [self modifySystemBathtub:number andPerson:item.person_number inSeciont:indexPath.section];
        };
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    else if (indexPath.row == 2) {
        //人数cell
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        [cell setTitle:@"人数"];
        [cell setNumber:item.person_number andUnit:@"人"];
        cell.SteperValueChangedBlock = ^(int number){
            [self modifySystemBathtub:item.bathtub_number andPerson:number inSeciont:indexPath.section];
        };
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    } else if (indexPath.row == 3) {
        //机型选择
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"edit"];
        [cell setTitleStr:@"空气能热水机" andColor:BSBlackTextColor andHintStr:nil andInputViewIsHidden:YES andInfoStr:nil andUnit:nil];
        [cell setNavigationHint:@"请选择"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    else {
        //设备cell
        //设备cell
        NSInteger equipIndex = indexPath.row - 4;
        KqnrsjEquipData *data = [item.equips objectAtIndex:equipIndex];
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        [cell setNumber:data.count andUnit:@"台"];
        [cell setTitle:data.equip_model];
        cell.SteperValueChangedBlock = ^(int number){
            if (number > 0) {
                [self updateKqnrsjEquipCount:number andSection:indexPath.section andIndex:equipIndex];
            } else {
                [self deleteKqnrsjSystemEquip:indexPath.section inIndex:equipIndex];
            }
        };
        //滑动按钮
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.tag = 100*indexPath.section + equipIndex;
        return cell;
    }
    return nil;
    
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"删除"];
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 3) {
        //机型选择
        KqnrsjSystemData *item =  [kProject.kqnrsj_systems objectAtIndex:indexPath.section];
        ProductListViewController *vc = [ProductListViewController new];
        vc.product_type = @"kqnrsj_equip";
        vc.title = @"选择空气能热水器";
        vc.series = kProject.kqnrsj_series;
        if (item.equips.count > 0) {
            vc.selectedGuids = [NSMutableArray new];
            for (KqnrsjEquipData *data in item.equips) {
                [vc.selectedGuids addObject:data.equip_id];
            }
        }
        vc.machineSelectedBlock = ^(NSArray *equips) {
            [self updateKqnrsjEquip:equips inSection:indexPath.section];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)updateKqnrsjEquip:(NSArray *)equips inSection:(NSInteger)section{
    KqnrsjSystemData *item =  [kProject.kqnrsj_systems objectAtIndex:section];
    NSMutableArray *ids = [NSMutableArray new];
    if (equips != nil && equips.count > 0) {
        for (NSDictionary *sel in equips) {
            [ids addObject:[sel objectForKey:@"Id"]];
        }
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    if (ids.count > 0) {
        [param setObject:[ids componentsJoinedByString:@","] forKey:@"ids"];
    } else {
        [param setObject:@"" forKey:@"ids"];
    }
    [param setObject:item.project_kqnrsj_system_id forKey:@"project_kqnrsj_system_id"];
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_KQNRSJ_SYSTEM_EQUIP_SET token:[AccountManager manager].token paramDic:param resultClass:[KqnrsjSystemData class] success:^(KqnrsjSystemData *obj) {
        //oc对象归档
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.kqnrsj_systems replaceObjectAtIndex:section withObject:obj];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"数据提交失败！"];
    }];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        //配置cell
        SystemConfigTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"system"];
        return [cell1 getHeight];
    } else if (indexPath.row == 1) {
        //浴缸
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        return [cell getHeigh];
    } else if (indexPath.row == 2) {
        //人数
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        return [cell getHeigh];
    } else if (indexPath.row == 3) {
        //机型选择
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"edit"];
        return [cell getHeight];
    } else {
        //设备cell
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        return [cell getHeigh];
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, DEFAULT_SECTION_HEIGHT)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return DEFAULT_SECTION_HEIGHT;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


#pragma mark - 滑动按钮代理协议
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    if (cell.tag >= 1000) {
        //删除系统
        [self deleteKqnrsjSystem:cell.tag - 1000];
    } else {
        //删除设备
        NSInteger section = cell.tag/100;
        NSInteger index = cell.tag%100;
        [self deleteKqnrsjSystemEquip:section inIndex:index];
    }
    [cell hideUtilityButtonsAnimated:YES];
}

- (void)deleteKqnrsjSystemEquip:(NSInteger)section inIndex:(NSInteger)index {
    KqnrsjSystemData *system = [kProject.kqnrsj_systems objectAtIndex:section];
    KqnrsjEquipData *equip = [system.equips objectAtIndex:index];
    NSMutableArray *ids = [NSMutableArray new];
    for (KqnrsjEquipData *item in system.equips) {
        if (![[item equip_id] isEqualToString:[equip equip_id]]) {
            [ids addObject:[item equip_id]];
        }
    }
    if (ids.count > 0) {
        [self setKqnrsjEquip:section andEquips:[ids componentsJoinedByString:@","]];
    } else {
        [self setKqnrsjEquip:section andEquips:@""];
    }
}

- (void)deleteKqnrsjSystem:(NSInteger)section{
    KqnrsjSystemData *system = [kProject.kqnrsj_systems objectAtIndex:section];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[system project_kqnrsj_system_id] forKey:@"project_kqnrsj_system_id"];
    [params setValue:kProject.project_id forKey:@"project_id"];
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_KQNRSJ_SYSTEM_DELETE token:[AccountManager manager].token paramDic:params resultClass:[KqnrsjSystemData class] success:^(KqnrsjSystemData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.kqnrsj_systems removeObjectAtIndex:section];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"删除失败！"];
    }];
}

- (void)setKqnrsjEquip:(NSInteger)section andEquips:(NSString*)ids {
    KqnrsjSystemData *system = [kProject.kqnrsj_systems objectAtIndex:section];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[system project_kqnrsj_system_id] forKey:@"project_kqnrsj_system_id"];
    [params setValue:ids forKey:@"ids"];
    
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_KQNRSJ_SYSTEM_EQUIP_SET token:[AccountManager manager].token paramDic:params resultClass:[KqnrsjSystemData class] success:^(KqnrsjSystemData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.kqnrsj_systems replaceObjectAtIndex:section withObject:obj];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"设置失败！"];
    }];
}

- (void)updateKqnrsjEquipCount:(NSInteger)count andSection:(NSInteger)section andIndex:(NSInteger)index {
    KqnrsjSystemData *system = [kProject.kqnrsj_systems objectAtIndex:section];
    KqnrsjEquipData *equip = [system.equips objectAtIndex:index];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[system project_kqnrsj_system_id] forKey:@"project_kqnrsj_system_id"];
    [params setValue:[equip equip_id] forKey:@"equip_id"];
    [params setValue:@(count) forKey:@"count"];
    
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_KQNRSJ_SYSTEM_EQUIP_COUNT token:[AccountManager manager].token paramDic:params resultClass:[KqnrsjSystemData class] success:^(KqnrsjSystemData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.kqnrsj_systems replaceObjectAtIndex:section withObject:obj];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"修改失败！"];
    }];
}
/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
